#include "mouse.h"
#include "compat.h"
#include "kbc.h"

static unsigned int x_ant = 0;
static unsigned int y_ant = 0;
static unsigned int x_pos = 0;
static unsigned int y_pos = 0;
static int click = 0;

void drawMouse( int * backup , char * video_base )
{
	if ( x_ant == x_pos && y_ant == y_pos)
		return;
	set_pixel( x_ant , y_ant , backup[0] , video_base );
	set_pixel( x_ant , y_ant + 1 , backup[1] , video_base );
	set_pixel( x_ant + 1 , y_ant , backup[2] , video_base );
	set_pixel( x_ant + 1 , y_ant + 1 , backup[3] , video_base );
	x_ant = x_pos;
	y_ant = y_pos;
	saveStat( x_ant , y_ant , backup , video_base );
	set_pixel( x_ant , y_ant , FORECOLOR , video_base );
	set_pixel( x_ant , y_ant + 1 , FORECOLOR , video_base );
	set_pixel( x_ant + 1 , y_ant , FORECOLOR , video_base );
	set_pixel( x_ant + 1 , y_ant + 1, FORECOLOR , video_base );
}

void saveStat( int x , int y , int * backup , char * video_base )
{
	backup[0] = get_pixel( x , y , video_base);
	backup[1] = get_pixel( x , y + 1 , video_base);
	backup[2] = get_pixel( x + 1 , y , video_base);
	backup[3] = get_pixel( x + 1 , y + 1 , video_base);
}

void parse_mouse_event( uchar * mouse )
{
	Byte Byte1 = mouse[0];
	Byte Byte2 = mouse[1];
	Byte Byte3 = mouse[2];
	x_pos += Byte1 & XSGN ? (Byte2 - 256) : Byte2;
	y_pos -= Byte1 & YSGN ? (Byte3 - 256) : Byte3;

	if ( x_pos >= HRES)
		x_pos = HRES-1;
	if ( x_pos <0 )
		x_pos = 0;
	if ( y_pos >= VRES )
		y_pos = VRES -1;
	if ( y_pos < 0 )
		y_pos = 0;
	click = LEFT_BUTTON(Byte1);
}

Bool insideOption( int x , int y , Option * op)
{
    if ( x > op->x_f )
        return false;
    if ( x < op->x_i )
        return false;
    if ( y > op->y_f )
        return false;
    if ( y < op->y_i )
        return false;
    return true;
}

int evaluateMouse( Menu * menu )
{
  int i = 0 ,j = 0 , ret;
  for ( i = 0; i < menu->num_options ; ++i )
    if ( insideOption( x_pos , y_pos , &menu->list[i] ) )
    {
		if ( menu->list[i].select == 1 )
		{
			ret =  click==1?2:0;
			click = 0;
			return ret;
		}
		for ( j = 0; j  < menu->num_options ; ++j )
			if ( j != i )
				menu->list[j].select = 0;
      menu->list[i].select = 1;
      ret = click==1?2:1;
	  click = 0;
	  return ret;
    }
  return 0;
}
